package com.afdor.rws.event.serialization;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.Event;
import com.afdor.rws.event.Serialization;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;

/**
 * 基于阿里云MQ的消息序列化器
 *
 * @author 悭梵
 * @date Created in 2018-08-16 19:12
 */
@Extension(value = "fastjson", order = Extension.NORMAL_ORDER - 100, interfaceClass = Serialization.class)
public class FastjsonSerialization implements Serialization<String> {
    @Override
    public Class<String> getOutClass() {
        return String.class;
    }

    @Override
    public String getContentType() {
        return "application/json;charset=utf-8;impl=event-fastjson";
    }

    @Override
    public String serialize(Event data) {
        return JSON.toJSONString(data);
    }

    @Override
    public Event unserialize(String data) {
        if (data == null || (data = data.trim()).length() == 0) {
            return null;
        }
        return JSON.parseObject(data, Event.class, Feature.OrderedField);
    }
}
